package com.example.test;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.View;

import androidx.appcompat.widget.AppCompatImageView;

import java.lang.reflect.Field;

public class FrameView extends AppCompatImageView {
    private AnimationDrawable run;

    public FrameView(Context context) {
        super(context);
    }

    public FrameView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FrameView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setRun(AnimationDrawable run){
        this.run = run;
    }

    //显示出图片的大小
    public void setLocation(int top, int left){
        this.setFrame(left,top,left + 200, top +250);
    }

    @Override
    protected void onDraw(Canvas canvas){
        try {
            //反射调用AnimationDrawable里的mCurFrame值
            Field field = AnimationDrawable.class.getDeclaredField("mCurFrame");
            field.setAccessible(true);
            int curFrame = field.getInt(run);//获取动画当前的帧
            if (curFrame == run.getNumberOfFrames() -1){//如果到了最后一帧
                //让该View隐藏
                setVisibility(View.INVISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDraw(canvas);
    }
}
